package com.example.controller;

import com.example.service.ConnectionService;
import com.example.util.ReturnJson;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/connection")
public class ConnectionController {

    @Autowired
    private ConnectionService connectionService;

    @ApiOperation("连接成功数据库中的单表的数据")
    @GetMapping(path = "/tableData")
    public ReturnJson tableData(@RequestParam(defaultValue = "1") Integer current,
                                @RequestParam(defaultValue = "10") Integer size,
                                @RequestParam Integer connectionId, @RequestParam String tableName) {
        // 根据 connectionId 获取数据库连接配置
        Connection connectionConfig = connectionService.getOne(new QueryWrapper<Connection>().eq("id", connectionId));
        if (connectionConfig == null) {
            return ReturnJson.fail("数据库连接配置不存在");
        }

        // 建立数据库连接
        ReturnJson connectionResult = connectionService.connection(connectionConfig);
        java.sql.Connection dbConnection = (java.sql.Connection) connectionResult.getData();
        if (dbConnection == null) {
            return ReturnJson.fail("数据库连接失败");
        }

        try (Statement statement = dbConnection.createStatement()) {
            // 获取表结构信息
            String descSql = "SELECT * FROM " + tableName + " LIMIT 0";
            ResultSet resultSet = statement.executeQuery(descSql);
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();
            
            // 获取列名列表
            List<String> columnNames = new ArrayList<>();
            for (int i = 1; i <= columnCount; i++) {
                columnNames.add(resultSetMetaData.getColumnName(i));
            }

            // 计算偏移量
            int offset = (current - 1) * size;
            // 构建带分页的查询语句
            String sql = "SELECT * FROM " + tableName + " ORDER BY id LIMIT " + size + " OFFSET " + offset;
            resultSet = statement.executeQuery(sql);

            List<Map<String, Object>> tableData = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = resultSetMetaData.getColumnName(i);
                    Object columnValue = resultSet.getObject(i);
                    row.put(columnName, columnValue);
                }
                tableData.add(row);
            }

            // 获取总记录数
            String countSql = "SELECT COUNT(*) FROM " + tableName;
            ResultSet countResultSet = statement.executeQuery(countSql);
            int total = 0;
            if (countResultSet.next()) {
                total = countResultSet.getInt(1);
            }

            // 封装分页信息
            Map<String, Object> pageInfo = new HashMap<>();
            pageInfo.put("current", current);
            pageInfo.put("size", size);
            pageInfo.put("total", total);
            pageInfo.put("records", tableData);
            pageInfo.put("columns", columnNames); // 添加列名信息

            return ReturnJson.success("获取单表数据成功", pageInfo);
        } catch (Exception e) {
            log.error("数据库操作失败: {}", e.getMessage());
            return ReturnJson.fail("数据库操作失败: " + e.getMessage());
        } finally {
            try {
                if (dbConnection != null) {
                    dbConnection.close();
                }
            } catch (Exception e) {
                log.error("关闭数据库连接失败: {}", e.getMessage());
            }
        }
    }
} 